package com.xp.record25.bio.netty.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.util.Objects;

public class NettyServer {
    public static void main(String[] args) {
        NioEventLoopGroup group = null;
        try{
            group = new NioEventLoopGroup();
            ChannelFuture channelFuture = new ServerBootstrap()
                    //设置线程轮询组
                    .group(group)
                    //设置连接实现类
                    .channel(NioServerSocketChannel.class)
                    //设置消息处理器 ChannelInitializer 是一个特殊的handler 当连接建立的时候触发
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            //Encoder 还必须再接收方才行
//                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                    System.out.println("msg = " + msg);
                                }
                            });
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    ByteBuf buffer = (ByteBuf) msg;
                                    System.out.println("buffer.toString() = " + buffer.toString());
                                }
                            });
                        }
                    })
                    //指定服务端口
                    .bind(8888).sync()  ;
            System.out.println("等待连接 端口 8888");
            channelFuture
                    //等待连接建立
                    .sync();
            System.out.println("连接成功 端口 8888"+channelFuture);
            Channel channel = channelFuture
                    //连接建立得到 channel
                    .channel();
            System.out.println("channel = " + channel);
            //等到关闭
            channel.closeFuture().sync();
            System.out.println("服务端已关闭");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (Objects.nonNull(group)) {
                group.shutdownGracefully();
            }
        }
    }
}
